package com.redis.data.seckillshopping.service.impl;

import com.redis.data.seckillshopping.dao.GoodsDao;
import com.redis.data.seckillshopping.entity.Goods;
import com.redis.data.seckillshopping.service.GoodsService;
import com.redis.data.seckillshopping.utils.JsonUtil;
import com.redis.data.seckillshopping.utils.RedisUtil;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 哲思小辉
 * @version 1.0.0
 * @ClassName GoodsServiceImpl.java
 * @Description 商品服务接口实现
 * @Param
 * @createTime 2020年03月25日 20:35:00
 */
@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    private GoodsDao goodsDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Goods queryById(Integer id) {
        return getGoods(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Goods> queryAllByLimit(int offset, int limit) {
        return this.goodsDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @Override
    public Goods insert(Goods goods) {
        this.goodsDao.insert(goods);
        return goods;
    }

    /**
     * 修改数据
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @Override
    public Goods update(Goods goods) {
        this.goodsDao.update(goods);
        return this.queryById(goods.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.goodsDao.deleteById(id) > 0;
    }


    private Goods getGoods(Integer goodsId) {
        val goods = RedisUtil.get(goodsId);
        if (goods == null || StringUtils.isBlank(goods.toString())) {
            boolean b = RedisUtil.tryLock(goodsId.toString());
            if (b) {
                val good = RedisUtil.get(goodsId);
                if (good != null && StringUtils.isNotBlank(good.toString())) {
                    return JsonUtil.toJavaBean(good, Goods.class);
                }
                val goo = goodsDao.queryById(goodsId);
                RedisUtil.set(goodsId, JsonUtil.toJson(goo));
                RedisUtil.unLock(goodsId.toString());
                return goo;
            }
        }
        return JsonUtil.toJavaBean(goods, Goods.class);
    }
}